#!/usr/bin/perl

use strict;

use List::Util qw(reduce);
use Data::Dumper;
use Math::Matrix;

use MGD;

my $file = $ARGV[0];
my $node = $ARGV[1];
my $fields = $ARGV[2];

my @data = load_data($file, $node, $fields);
print Dumper(\@data);

my $px = MGD::ComputeMGD(\@data);
print "Probilities\tDelta\tV1\tV2\t...\n";
print Math::Matrix->new(@$px);
print "\n\n";

my %probs;
for my $p ( @$px ) {
    $probs{ join("/", @$p[2 .. $#$p]) } = $p->[0];
}

for my $key (sort {$probs{$a} <=> $probs{$b}} keys %probs) {
    print "$key, $probs{$key}\n";
}

print "probs:", (reduce {$a + $b}  values %probs), "\n";


sub load_data {
    my ($file, $node, $fields) = @_;
    open my $fh, "<", $file or die "Could not open file $file\n";

    my @data = ();
    while (<$fh>) {
        next if ($node ne "ALL" &&  $_ !~ /$node/);

        chomp;

        my @items = split /,\s*/;
        my @fields = split /,/, $fields;

        push @data, [ @items[@fields] ];
    }

    return @data;
}
